<template>
    <div>
        <div class="searchFileDiv">
            <div>
                &nbsp;
                <Input v-model="filePath" placeholder="请选择文件夹" style="width: 60%"/>
                <Button type="default" ghost size="small" @click="selectFolder()">文件夹</Button>
            </div>
            <div>
                <Input v-model="searchContent" placeholder="请输入文件名或备注内容" @keyup.enter.native="searchFile()" style="width: 60%"/>
                <Button type="primary" size="small" @click="searchFile()" :loading="searchLoading" style="background-color: #CDC673; border: 0px;">
                    <img src="~@/assets/icon/search.png" width="30px" height="30px">
                </Button>
            </div>
        </div>
        <div class="fileContent">
            <div style="width: 100%;text-align: right;margin-bottom: 6px; color: #FFF">
                <span>共{{fileData.length}}个文件</span>
                <span style="color: red" v-if="fileData.length >= 200"><br>最多显示200个，后面可能还有更多，请精确条件搜索</span>
                <span style="color: red" v-if="count >= 20000"><br>搜索目录太多，已停止搜索，请选择较小文件夹</span>
                <br>
            </div>
            <Table @on-row-dblclick="openFile" height="400" :columns="columns" :data="fileData"></Table>
        </div>
    </div>
</template>
<script>
  import $ from 'jquery'
  const {dialog} = require('electron').remote
  const { shell } = require('electron').remote
  const path = require('path')
  const fs = require('fs')
  const Electron = require('electron')
  const remote = Electron.remote
  const Menu = remote.Menu
  const MenuItem = remote.MenuItem
  export default {
    name: 'SearchInFolder',
    components: {},
    data: function () {
      return {
        searchContent: '',
        fileData: [],
        filePath: '',
        toOpenPath: '',
        searchLoading: false,
        searchTimer: null,
        count: 0,
        columns: [
          {
            width: '1px'
          },
          {
            title: '文件名',
            key: 'file_name'
          },
          {
            title: '路径',
            key: 'file_path'
          }
        ]
      }
    },
    created () {
      console.info('初始化')
      console.info('menuFirstLoad', this.$store.state.menuFirstLoad)
      let loadFlag = this.$store.state.menuFirstLoad
      if (loadFlag === 'no') {
        this.$store.state.menuFirstLoad = 'yes'
        this.initMenu()
      }
    },
    methods: {
      initMenu () { // eslint-disable-line
        let that = this
        console.info('初始化菜单', that)
        const menu = new Menu()
        menu.append(new MenuItem({
          label: '打开',
          role: 'openFile',
          click: function (data) {
            console.info('打开文件abc', that.toOpenPath)
            shell.openItem(that.toOpenPath)
          }
        }))
        menu.append(new MenuItem({
          label: '打开路径',
          click: function (data) {
            console.info('打开路径abc', that.toOpenPath)
            shell.showItemInFolder(that.toOpenPath)
          }
        }))

        document.addEventListener('contextmenu', (e) => {
          e.preventDefault()
          console.info('使用that', that)
          if (this.isFileRecord(e.target, that)) {
            menu.popup(remote.getCurrentWindow())
          }
        }, false)
      },
      isFileRecord (e, that) {
        if (e) {
          if (e.tagName === 'TR') {
            console.info('判断对象:', e)
            console.info('打印e对象', $(e).find('td').eq(2).find('span').text())
            that.toOpenPath = $(e).find('td').eq(2).find('span').text()
            return true
          } else {
            // 递归查询父节点
            return this.isFileRecord(e.parentNode, that)
          }
        } else {
          return false
        }
        // 为input标签或者contenteditable属性为true
      },
      openFile (e) {
        shell.openItem(e.file_path)
      },
      searchFile: function () {
        console.info('test')
        if (!this.filePath) {
          this.$Message.warning('请选择文件夹')
          return
        }
        console.info('搜索内容为:', this.searchContent)
        if (this.searchContent) {
          let that = this
          if (this.searchTimer) {
            clearTimeout(this.searchTimer)
          }
          this.searchTimer = setTimeout(function () {
            that.searchLoading = false
          }, 3000)
          if (!this.searchLoading) {
            this.fileData = []
            this.count = 0
            this.mapDir(this.filePath, this.fileData, this.searchContent)
          }
          this.searchLoading = true
        } else {
          this.$Message.warning('请输入查询内容')
        }
      },
      selectFolder: function () {
        console.info('selectFolder')
        let that = this
        dialog.showOpenDialog({
          title: '选择文件夹', // 对话框的标题
          properties: ['openDirectory'], // 打开文件夹，默认打开文件，multiSelections可以多选
          filters: [
            {}
          ],
          buttonLabel: '选择文件夹' // 自定义按钮文本显示内容
        }, function (data) {
          console.log(data)
          if (data.length > 0) {
            that.filePath = data[0]
          }
        })
      },
      mapDir: function (dir, data, searchContent) {
        this.count++
        if (this.count > 20000) {
          return
        }
        if (this.count > 10000 && this.count % 1000 === 0) {
          console.info('遍历次数', this.count)
          setTimeout(function () {
            this.mapDir(dir, data, searchContent)
          }, 0)
          return
        }
        if (data.length > 200) {
          return
        }
        // console.info('正在遍历', dir)
        let files = fs.readdirSync(dir)
        files.forEach((filename, index) => {
          let pathname = path.join(dir, filename)
          // console.info('遍历子文件', pathname)
          fs.stat(pathname, (err, stats) => {
            if (err) {
              console.log('获取文件stats失败')
              return
            } if (stats.isDirectory()) {
              this.mapDir(pathname, data, searchContent)
            } else if (stats.isFile() && filename.indexOf(searchContent) > -1) {
              let file = {
                file_name: filename,
                file_path: pathname
              }
              if (data.length < 200) {
                data.push(file)
              }
            }
          })
        })
      }
    }
  }
</script>

<style scoped>
    .searchFileDiv {
        width: 100%;
        margin-top: 30px;
        margin-left: auto;
        margin-right: auto;
        text-align: center;
    }
    .fileContent {
        margin-top: 0px;
        width: 97%;
        text-align: center;
        margin-left: auto;
        margin-right: auto;
    }
</style>
